package com.wolfeyes.common.utils.network.web;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wolfeyes.common.response.ResponseResult;
import com.wolfeyes.common.utils.network.http.ServletUtils;

import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
//import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;

@NoArgsConstructor
public class ResponseUtils {

	private static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

	private static final ObjectMapper objectMapper = new ObjectMapper();
	
	/*
	public ResponseUtils() {
	
	}
	*/

	public static void out(ResponseResult result) {
		out(200, result, (Map) null);
	}

	public static void out(int statusCode, ResponseResult result) {
		out(statusCode, result, (Map) null);
	}

	public static void outWithHeader(int statusCode, ResponseResult result, Map<String, String> map) {
		out(statusCode, result, map);
	}

	public static void out(int statusCode, ResponseResult result, Map<String, String> header) {
		
		ServletOutputStream out = null;

		try {
			//ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
			//if (servletRequestAttributes != null) {
			//HttpServletResponse response = servletRequestAttributes.getResponse();
			HttpServletResponse httpServletResponse = ServletUtils.getResponse();
			if (httpServletResponse != null && !httpServletResponse.isCommitted()) {
			//如果发现乱码,这里注释
				httpServletResponse.setCharacterEncoding("UTF-8");
				//处理编码方式，防止中文乱码的情况
				httpServletResponse.setContentType("application/json;charset=UTF-8");
				httpServletResponse.setStatus(statusCode);
				if (MapUtils.isNotEmpty(header)) {
					header.forEach(httpServletResponse::setHeader);
				}

				out = httpServletResponse.getOutputStream();
				out.write(JSON.toJSONString(result).getBytes());
			}
			//}
		} catch (Exception e) {
			log.error("[ResponseUtils] 响应出错 ", e);
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					log.error("关闭流出错 ", e);
				}
			}
		}
	}

	public static void result(HttpServletResponse response, ResponseResult responseResult) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		ServletOutputStream out = response.getOutputStream();
		//ObjectMapper objectMapper = new ObjectMapper();
		out.write(objectMapper.writeValueAsString(responseResult).getBytes("UTF-8"));
		out.flush();
		out.close();
	}

}

